const { create, query } = require('../../helper/db');
const { encrypt, now, ok } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 登录注册
 * @api {POST} api/signup 注册
 * @apiName api/signup
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/signup', {
 *    username: 'gmonking',
 *    password: '123456',
 *  });
 * @apiParam  {String} username 用户名称
 * @apiParam  {String} password 用户密码
 * @apiSuccess (请求成功) {String} token 用户令牌
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var params = ctx.request.body;
  var userlist = await query('select * from user where username = ?', [params.username]);

  if (userlist.length) {
    throw new Error('用户名已存在');
  }

  var encrypedPassword = encrypt('password', params.password);
  var user = await create('user', {
    username: params.username,
    password: encrypedPassword,
    nickname: '',
    message: '',
    email: '',
    age: 0,
    avatar: '',
    status: 0,
    createdat: now(),
  });

  ctx.body = ok({
    token: encrypt('user', user.id),
  });
}